<template>
  <div style="width: calc(100% - 40px); padding: 20px; background-color: #fff; height: auto">
    <!-- 公用表头组件 -->
    <el-card class="box-card">
      <CommonForm v-if="isRouterAlive" />
    </el-card>
    <!-- 公共导航 -->
    <el-card>
      <NavTab />
    </el-card>
    <!-- 表单 -->
    <el-card class="box-card">
      <div class="text item" style="margin-bottom: 50px">
        <el-form ref="form" class="form" :disabled="showData" :label-position="labelPosition" :model="form" :rules="rules">
          <el-form-item label="集中控制费用" prop="CENTRALIZED_PRICE" style="margin-right: 60px; width: 320px">
            <el-input v-model="form.CENTRALIZED_PRICE" class="num_input1" clearable />
          </el-form-item>
          <el-form-item label="合同备件" prop="TOTAL_PRICE" style="margin-right: 20px; width: 200px">
            <div style="display: flex">
              <el-radio v-model="radio" label="1">excel导入</el-radio>
              <el-radio v-model="radio" label="2">百分比计算</el-radio>
              <el-radio v-model="radio" label="3">填写总金额</el-radio>
            </div>
            <div>
              <div v-if="radio == 1" style="width: 100%">
                <div style="border: 1px dashed #ccc; width: 255%; height: 80px; text-align: center; line-height: 40px" @click="handleClick">
                  <span>备品模板</span>
                  <span style="font-size: 12px; color: #ccc">请按照数据模板的格式准备导入数据 下载模板</span>
                  <!-- <p style="color: #409eff; cursor: pointer; user-select: none"><em>备品模板</em></p> -->
                  <el-button size="mini" type="text" @click="clickUpload">下载模板</el-button>
                </div>
                <br />
                <div style="width: 255%; border: 1px dashed #ccc; text-align: center">
                  <p>
                    <span>上传附件</span>
                    <span style="font-size: 12px; color: rgb(206, 202, 202)">文件后缀名必须为xls 或xlsx （即Excel格式）</span>
                  </p>
                  <vui-upload
                    ref="fileUploadRefForm"
                    class="text-left"
                    :file-name="uploadOptions.name"
                    :limit="1"
                    :post-data="uploadOptions.postData"
                    style="text-align: center"
                    :url="uploadOptions.url"
                    @uploadSuccess="uploadSuccessForm"
                  >
                    <!-- <div style="text-align: center; padding: 10px"> -->
                    <el-button type="text">选择文件</el-button>
                    <!-- </div> -->
                  </vui-upload>
                  <el-button type="text" @click="clickUpload('fileUploadRefForm')">上传文件</el-button>
                </div>
                <el-input v-model="form.TOTAL_PRICE" class="percentage" clearable disabled placeholder="合计金额" />
              </div>
              <div v-if="radio == 2">
                <div style="display: flex; width: 320%; margin-top: 10px">
                  <el-input v-model="form.PRICE" clearable disabled placeholder="金额" @keyup="onChange2" />
                  <span style="text-align: center; margin-top: 5px; margin-left: 10px; margin-right: 10px">*</span>
                  <div style="position: relative">
                    <el-input v-model="form.PERCENT" clearable placeholder="请输入百分比" @keyup="onChange2" />
                    <span style="position: absolute; top: 6%; right: -14%; display: table-cell; white-space: nowrap">%</span>
                  </div>
                </div>
                <el-input v-model="form.TOTAL_PRICE" class="percentage" clearable disabled placeholder="合计金额" />
              </div>
              <div v-if="radio == 3"><el-input v-model="form.TOTAL_PRICE" class="percentage" clearable placeholder="合计金额" /></div>
            </div>
          </el-form-item>
          <el-form-item label="现场费用" prop="FIELD_COST" style="margin-right: 60px; width: 400px">
            <el-input v-model="form.FIELD_COST" class="num_input1" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="合同保驾" prop="CONTRACT_MANDAY" style="margin-right: 20px">
            <p style="display: flex">
              <el-input v-model="form.CONTRACT_MANDAY" class="percent" placeholder="人天单价" @keyup="onChange" />
              <span style="text-align: center; margin-top: 2px; margin-left: 10px; margin-right: 10px">*</span>
              <el-input v-model="form.CONTRACT_DAY" class="percent" placeholder="天数" @keyup="onChange" />
              <span style="text-align: center; margin-top: 2px; margin-left: 10px; margin-right: 10px">=</span>
              <el-input v-model="form.CONTRACT_COST" class="percent" clearable disabled placeholder="总价" />
            </p>
          </el-form-item>
          <el-form-item label="质保费用" prop="WARRANTY_PERCENT" style="margin-right: 60px">
            <div style="display: flex; position: relative">
              <el-input v-model="form.WARRANTY_PROCE" class="percent" clearable disabled placeholder="金额" @keyup="onChange1" />
              <span style="text-align: center; margin-top: 2px; margin-left: 10px; margin-right: 10px">*</span>
              <div style="position: relative">
                <el-input v-model="form.WARRANTY_PERCENT" class="percent" clearable placeholder="请输入百分比" @keyup="onChange1" />
                <span style="position: absolute; top: 8%; right: 30%; display: table-cell; white-space: nowrap">%</span>
              </div>
              <span style="text-align: center; margin-top: 2px; margin-left: 10px; margin-right: 10px">=</span>
              <el-input v-model="form.WARRANTY_COST" class="percent" clearable disabled placeholder="费用" />
            </div>
          </el-form-item>
          <el-form-item label="利旧费用" prop="OLD_COST" style="display: flex">
            <el-input v-model="form.OLD_COST" class="Brand_discount" clearable placeholder="请输入" style="width: 210px" />
          </el-form-item>
          <el-form-item label="运输费用" prop="TRANSPORT_COST" style="margin-right: 20px; width: 286px">
            <el-input v-model="form.TRANSPORT_COST" class="num_input1" clearable />
          </el-form-item>
          <el-form-item style="margin-right: 20px; display: block">
            <div style="border: 1px dashed #ccc; width: 60%; text-align: center">
              <p>
                <span>上传利旧附件</span>
                <span style="font-size: 12px; color: rgb(206, 202, 202)">文件后缀名必须为xls 或xlsx （即Excel格式）</span>
              </p>
              <vui-upload
                ref="fileUploadRef"
                class="text-left"
                :file-name="uploadOptions.name"
                :limit="1"
                :post-data="uploadOptions.postData"
                style="text-align: center"
                :url="uploadOptions.url"
                @uploadSuccess="uploadSuccess"
              >
                <div style="padding: 10px">
                  <el-button type="text">选择文件</el-button>
                </div>
              </vui-upload>
              <el-button size="mini" type="text" @click="clickUpload('fileUploadRef')">上传文件</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: flex; justify-content: center; padding-bottom: 20px">
        <el-button :disabled="showData" @click="resetForm('form')">
          <vui-icon icon="refresh-line" />
          重置
        </el-button>
        <el-button :disabled="showData" type="primary" @click="handlePreservat">
          <vui-icon icon="save-line" />
          保存
        </el-button>
        <el-button v-show="show" :disabled="disabledForm" type="primary" @click="handlePublishData">发布数据</el-button>
        <el-button v-show="showData" :disabled="disabledForm2" type="danger" @click="open">撤消发布</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
  import CommonForm from '@/project/bqms/components/ComTable.vue'
  import NavTab from '@/project/bqms/components/NavTab.vue'
  import { getList, download } from '../api/home.js'
  import { GFCD } from '@/utils/utils'
  import { defineComponent } from 'vue'
  const configSetting = GFCD('bqms')
  export default defineComponent({
    name: 'OtherExpense',
    components: {
      CommonForm,
      NavTab,
    },
    data() {
      return {
        disabledForm1: true,
        isRouterAlive: true,
        uploadOptions: {
          postData: {
            method: 'bqms.file.upload',
            data: '{}',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        uploadOption: {
          postData: {
            method: 'bqms.file.upload',
            data: '{}',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        // bobby end
        labelPosition: 'left',
        radio: '1',
        disabled: false,
        showData: false,
        show: true,
        disabledForm: false,
        gridData: [],
        validList: [
          'CENTRALIZED_PRICE',
          'FIELD_COST',
          'CONTRACT_COST',
          'WARRANTY_COST',
          'OLD_COST',
          'TOTAL_PRICE',
          'TRANSPORT_COST',
          'WARRANTY_PROCE',
          'WARRANTY_PERCENT',
          'CONTRACT_DAY',
          'CONTRACT_MANDAY',
        ],
        form: {
          CENTRALIZED_PRICE: '', //集中控制费用
          FIELD_COST: '', //现场费用
          CONTRACT_COST: '', //合同保驾
          WARRANTY_COST: '', //质保费用
          OLD_COST: '', //利旧费用
          TOTAL_PRICE: '', //合同备件--合计金额
          TRANSPORT_COST: '', //运输费用
          WARRANTY_PROCE: '', //质保金额
          WARRANTY_PERCENT: '', //质保费用百分比
          CONTRACT_DAY: '', //合同人天数
          CONTRACT_MANDAY: '', //合同人天单价
          PRICE: '',
          PERCENT: '',
        },
        tabForm: {
          PRICE: '', //合同备件--金额
          PERCENT: '', //合同备件--百分比
          TOTAL_PRICE: 0, //合同备件--百分比
          COUNTRESULT: '',
        },
        uploadInfo: {}, //附件
        oldUploadInfo: {}, //利旧附件
        fileList1: [],
        limitNum: 1,
        formLabelWidth: '80px',
        fileList: [],
        url: '',
        data: {},
        file: {},
        rules: {
          CENTRALIZED_PRICE: [{ required: true, message: '请输入集中控制费用', trigger: 'blur' }, { trigger: 'blur' }],
          // TOTAL_PRICE: [{ required: true, message: '请输入合同备件', trigger: 'blur' }, { trigger: 'blur' }],
          FIELD_COST: [{ required: true, message: '请输入现场费用', trigger: 'blur' }, { trigger: 'blur' }],
          CONTRACT_COST: [{ required: true, message: '请输入合同保驾', trigger: 'blur' }, { trigger: 'blur' }],
          WARRANTY_PERCENT: [{ required: true, message: '请输入质保百分比', trigger: 'blur' }, { trigger: 'blur' }],
          OLD_COST: [{ required: true, message: '请输入利旧费用', trigger: 'blur' }, { trigger: 'blur' }],
          TRANSPORT_COST: [{ required: true, message: '请输入运输费用', trigger: 'blur' }, { trigger: 'blur' }],
          WARRANTY_PROCE: [{ required: true, message: '请输入质保金额', trigger: 'blur' }, { trigger: 'blur' }],
          CONTRACT_MANDAY: [{ required: true, message: '请输入人天单价', trigger: 'blur' }, { trigger: 'blur' }],
          CONTRACT_DAY: [{ required: true, message: '请输入天数', trigger: 'blur' }, { trigger: 'blur' }],
        },
      }
    },
    activated() {
      this.getAmountMoneyData()
      this.isRouterAlive = false
      this.$nextTick(() => (this.isRouterAlive = true))
      console.log(this.$store.getters['bqmsData/HeaderTable'])
    },
    created() {
      this.getAmountMoneyData()
    },
    methods: {
      clickUpload(reFname) {
        this.$refs[reFname].submitUpload()
      },
      //下载模板
      async handleClick() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: 'bqms.temp.download',
          data: JSON.stringify({ TEMP_TYPE: 'SPARE_PARTS' }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '合同备件模板.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      open() {
        this.$confirm('是否撤销发布', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.getRevokePublicatData() //撤销发布接口
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消撤销发布',
            })
          })
      },
      getAmountMoneyData() {
        let AmountMoneyData = this.$store.getters['bqmsData/HeaderTable']
        console.log('其他费用', AmountMoneyData)
        console.log('AmountMoneyData', AmountMoneyData)
        // this.form.WARRANTY_PROCE = AmountMoneyData.WARRANTY_PROCE //质保金额
        // console.log('this.form.WARRANTY_PROCE', AmountMoneyData.WARRANTY_PROCE, this.form.WARRANTY_PROCE)
        // this.form.PRICE = AmountMoneyData.PRICE //合同备件
        this.form = AmountMoneyData
        this.form.WARRANTY_PROCE = Math.floor(this.form.WARRANTY_PROCE * 100) / 100
        this.form.WARRANTY_COST = Math.floor(this.form.WARRANTY_COST * 100) / 100
        this.form.TOTAL_PRICE = Math.floor(this.form.TOTAL_PRICE * 100) / 100
        this.form.PRICE = Math.floor(this.form.PRICE * 100) / 100
        if (this.$store.getters['bqmsData/HeaderTable'].OTHER_ISSUE == 'Y') {
          this.show = false
          this.showData = true //撤销发布
        } else {
          this.show = true
          this.showData = false
          this.disabledForm = true
        }
      },
      //成功回调(附件)
      uploadSuccess({ fileList }) {
        console.log('利旧附件上传完成', fileList[0].response)
        if (fileList[0].response.code == '00000') {
          this.$message({
            message: '上传成功！！！',
            type: 'success',
          })
          this.oldUploadInfo = fileList[0].response.data
        } else {
          this.$message({ type: 'error', message: fileList[0].response.msg })
        }
      },
      //成功回调(利旧附件)
      uploadSuccessForm({ fileList }) {
        console.log('附件上传完成', fileList[0].response)
        if (fileList[0].response.code == '00000') {
          this.$message({
            message: '上传成功！！！',
            type: 'success',
          })
          this.uploadInfo = fileList[0].response.data
          this.form.TOTAL_PRICE = fileList[0].response.data.countResult //合计金额
          console.log('合计金额', fileList[0].response.data.countResult)
        } else {
          this.$message({ type: 'error', message: fileList[0].response.msg })
        }
      },
      // 计算总价
      onChange(val) {
        this.form.CONTRACT_COST = parseFloat(this.form.CONTRACT_MANDAY) * parseFloat(this.form.CONTRACT_DAY) || 0 //合同价保
        console.log('val', val)
      },
      // 计算总价
      onChange1(val) {
        this.form.WARRANTY_COST = (parseFloat(this.form.WARRANTY_PROCE) * parseFloat(this.form.WARRANTY_PERCENT)) / 100 || 0 //质保费用
        console.log('val1', val)
      },
      // 计算总价D
      onChange2(val) {
        this.form.TOTAL_PRICE = (parseFloat(this.form.PRICE) * parseFloat(this.form.PERCENT)) / 100 || 0 //百分比计算
        console.log('val2', val)
      },
      //发布数据
      handlePublishData() {
        console.log('发布数据！！！')
        this.$confirm('是否确认发布', '发布数据', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.getValid(() => {
              this.handleDialogVisible()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消发布',
            })
          })
      },
      //确定
      handleDialogVisible() {
        // this.form.PRICE = this.tabForm.PRICE
        // this.form.PERCENT = this.tabForm.PERCENT
        console.log(this.form.PERCENT)
        let formFlag = false
        let formFlag1 = false
        for (const key in this.form) {
          const element = this.form[key]
          if (!element && element != 0) {
            formFlag = true
          }
        }
        for (const key in this.form) {
          const element = this.form[key]
          if (key != 'PRICE' && key != 'PERCENT') {
            if (!element && element != 0) formFlag1 = true
          }
        }
        if (this.radio == '2') {
          if (formFlag) {
            this.$message({
              message: '请把表格内容填写完整！！！',
              type: 'error',
            })
          } else {
            //走接口
            this.setDemo()
          }
        } else {
          console.log(22222)
          console.log(formFlag1)
          if (formFlag1) {
            console.log('触发了')
            this.$message({
              message: '请把表格内容填写完整！！！',
              type: 'error',
            })
          } else {
            console.log('走接口')
            //走接口
            this.setDemo()
          }
        }
      },
      //撤销发布
      getRevokePublicatData() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.common.reverseRelease'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
            TYPE: 'OTHER_ISSUE',
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.show = true //显示发布数据
            this.showData = false //隐藏撤销发布
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      getValid(fn) {
        let formFlag = false
        for (const key in this.form) {
          if (this.form[key] === '0') {
            this.form[key] = Number(this.form[key])
          }
        }
        this.validList.forEach((row) => {
          console.log('row', this.form[row], !this.form[row])
          if (!this.form[row] && this.form[row] !== 0) {
            formFlag = true
          }
        })
        if (this.radio == '2') {
          console.log(1111)
          if (formFlag && !this.form.PRICE && !this.form.PERCENT) {
            console.log('1-1')
            this.$message({
              message: '请把表格内容填写完整！！！',
              type: 'error',
            })
          } else {
            //走接口
            console.log('1-接口')
            fn()
          }
        } else {
          console.log(22222)
          if (formFlag) {
            console.log('2-1')
            this.$message({
              message: '请把表格内容填写完整！！！',
              type: 'error',
            })
          } else {
            console.log('走接口')
            //走接口
            fn()
          }
        }
      },
      //保存
      handlePreservat(formName) {
        console.log('formName', formName)
        this.getValid(() => {
          this.getSaveFormInfo()
        })
      },
      //保存数据
      getSaveFormInfo() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.other.fee.update'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            ...this.form,
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.disabledForm1 = false
            this.disabledForm = false
            console.log('其他费用保存表单数据', res.data)
            this.$pub(`topFormData`, true)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
      //重置
      resetForm() {
        // this.$refs[formName].resetFields()
        let oldForm = JSON.parse(JSON.stringify(this.form))
        this.form = {
          CENTRALIZED_PRICE: '', //集中控制费用
          FIELD_COST: '', //现场费用
          OLD_COST: '', //利旧费用
          TRANSPORT_COST: '', //运输费用
          WARRANTY_COST: '', //质保费用
          WARRANTY_PERCENT: '', //质保费用百分比
          // WARRANTY_PROCE: '', //质保金额
          CONTRACT_COST: '', //合同保驾
          CONTRACT_DAY: '', //合同人天数
          CONTRACT_MANDAY: '', //合同人天单价
          // countResult: '', //合计金额
          // PRICE: '',
          PERCENT: '',
        }
        this.form.WARRANTY_PROCE = oldForm.WARRANTY_PROCE
        this.form.countResult = oldForm.countResult
        this.form.PRICE = oldForm.PRICE

        this.tabForm = {
          PRICE: '', //合同备件--金额
          PERCENT: '', //合同备件--百分比
        }
        // this.tabForm = {
        //   // number: '', //合同备件--金额
        //   percentage: '', //合同备件--百分比
        // }
        // this.getAmountMoneyData()
      },
      setDemo() {
        this.configSetting = GFCD('bqms')
        let method = 'bqms.common.sp.release'
        getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({
            TYPE: 'OTHER_ISSUE',
            DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.showData = true
            this.show = false
            this.$pub(`topFormData`, true)
          } else {
            this.$message({ type: 'error', message: res.msg })
          }
        })
      },
    },
  })
</script>

<style lang="scss" scoped>
  .form {
    width: 70%;
    padding: 10px;

    .upload {
      display: flex;
      height: 80px !important;
      // border: 1px dashed #ccc !important;
      font-size: 14px;
      margin-bottom: 16px;
    }
    .percentage {
      width: 400px !important;
      margin-bottom: 16px;
      margin-top: 10px;
    }
    .percent {
      width: 200px !important;
    }
    .showData {
      position: absolute;
      top: 0;
      right: 0;
      width: 50px;
      height: 50px;
      background-color: #fff;
      // z-index: 10;
    }
  }
  .el-card__body {
    background-color: #fff;
  }
  .el-menu-demo {
    background-color: #fff !important;
    color: #000 !important;
  }
  // @import '@/project/bqms/static/scss/otherExpense.scss';
</style>
